import sys
import os
import subprocess

print("=" * 50)
print("虚拟环境完整诊断")
print("=" * 50)

print("\n1. 环境变量:")
print(f"   VIRTUAL_ENV: {os.environ.get('VIRTUAL_ENV', '未设置')}")
print(f"   PATH: {os.environ.get('PATH', '')}")

print("\n2. Python 信息:")
print(f"   可执行文件: {sys.executable}")
print(f"   版本: {sys.version}")

print("\n3. Python 路径:")
for i, path in enumerate(sys.path):
    print(f"   {i:2d}: {path}")

print("\n4. 虚拟环境文件检查:")
venv_path = os.environ.get('VIRTUAL_ENV', '')
if venv_path:
    print(f"   虚拟环境路径: {venv_path}")
    site_packages = f"{venv_path}/lib/python{sys.version_info.major}.{sys.version_info.minor}/site-packages"
    print(f"   Site-packages: {site_packages}")
    
    # 检查 site-packages 是否存在
    if os.path.exists(site_packages):
        print(f"   ✓ Site-packages 目录存在")
        # 列出一些已安装的包
        packages = os.listdir(site_packages)
        print(f"   找到 {len(packages)} 个包/目录")
        for pkg in sorted(packages)[:10]:  # 只显示前10个
            print(f"     - {pkg}")
    else:
        print(f"   ✗ Site-packages 目录不存在!")
else:
    print("   ✗ 虚拟环境未激活")

print("\n5. Pip 列表检查:")
try:
    result = subprocess.run([sys.executable, '-m', 'pip', 'list'], 
                          capture_output=True, text=True, timeout=30)
    if result.returncode == 0:
        print("   Pip 列表输出:")
        for line in result.stdout.split('\n')[:20]:  # 只显示前20行
            if line.strip():
                print(f"     {line}")
    else:
        print(f"   Pip 列表失败: {result.stderr}")
except Exception as e:
    print(f"   Pip 列表异常: {e}")

print("\n6. 包导入测试:")
test_packages = ['numpy', 'matplotlib', 'flask', 'flask_socketio']
for pkg in test_packages:
    try:
        module = __import__(pkg)
        file_path = getattr(module, '__file__', '内置模块')
        print(f"   ✓ {pkg:15} -> {file_path}")
    except ImportError as e:
        print(f"   ✗ {pkg:15} -> 导入失败: {e}")

print("\n" + "=" * 50)
